//
//  CrashListViewController.m
//  CrashSolveDemo
//
//  Created by 戚永超 on 15/12/1.
//  Copyright © 2015年 戚永超. All rights reserved.
//

#import "CrashListViewController.h"
#import "UncaughtExceptionHandler.h"
#import "UIImageView+PreviewImage.h"
#import <MessageUI/MFMailComposeViewController.h>
#import "HDEasterEggsCenterModelDefine.h"

@interface CrashListViewController() <MFMailComposeViewControllerDelegate>

@property (nonatomic, strong) NSArray *dataList;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation CrashListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];
    NSString *crashFielPath = [documentsPath stringByAppendingPathComponent:@"CrashDatas"];
    
    self.dataList = [NSMutableArray arrayWithContentsOfFile:crashFielPath];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *identifier = @"CrashListCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    UIImageView *crashImageView = (UIImageView *)[cell viewWithTag:100];
    UILabel *crashLabel = (UILabel *)[cell viewWithTag:200];
    UILabel *timeLabel = (UILabel *)[cell viewWithTag:300];

    NSDictionary *dic = self.dataList[indexPath.row];
    crashLabel.text = dic[@"crashString"];
    timeLabel.text = dic[@"timeString"];
    crashImageView.image = [UIImage imageWithData:dic[@"imageData"]];
    [crashImageView showPreviewImage];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 400*SCREEN_WIDTH/414.0f;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.dataList[indexPath.row];

    //发送邮件
    [self displayMailPicker:dic];

}

//调出邮件发送窗口
- (void)displayMailPicker:(NSDictionary *)crashInfo {
    
    //判断已经登录邮箱账号能否发送邮件，若没有使用外部发送以登录邮箱
    if (![MFMailComposeViewController canSendMail]) {
        
        NSMutableString *mailUrl = [[NSMutableString alloc]init];
        //添加收件人
        NSArray *toRecipients = [NSArray arrayWithObject: @"qiyongchao@haodai.com"];
        [mailUrl appendFormat:@"mailto:%@?", [toRecipients componentsJoinedByString:@","]];
//        //添加抄送
//        NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
//        [mailUrl appendFormat:@"?cc=%@", [ccRecipients componentsJoinedByString:@","]];
//        //添加密送
//        NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
//        [mailUrl appendFormat:@"&bcc=%@", [bccRecipients componentsJoinedByString:@","]];
        //添加主题
        [mailUrl appendString:@"&subject=iOS Bug报告"];
        //添加邮件内容
         NSString *emailBody = [NSString stringWithFormat:@"<font color='red'>%@\ncrashTime：%@</font>", crashInfo[@"crashString"],crashInfo[@"timeString"]];
        [mailUrl appendString:[NSString stringWithFormat:@"&body=%@",emailBody]];
        
        NSString* email = [mailUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        [[UIApplication sharedApplication] openURL: [NSURL URLWithString:email]];
        
        return;
        
    }
    
    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
//    mailPicker.navigationBar.tintColor = [UIColor whiteColor];
    mailPicker.mailComposeDelegate = self;
    
    //设置主题
    [mailPicker setSubject:[NSString stringWithFormat:@"iOS Bug报告"]];
    //添加收件人
    NSArray *toRecipients = [NSArray arrayWithObject: @"qiyongchao@haodai.com"];
    [mailPicker setToRecipients: toRecipients];
//    //添加抄送
//    NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
//    [mailPicker setCcRecipients:ccRecipients];
//    //添加密送
//    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
//    [mailPicker setBccRecipients:bccRecipients];
    
    
    // 添加一张图片
    [mailPicker addAttachmentData: crashInfo[@"imageData"] mimeType: @"" fileName: @"crash.jpg"];
    
    NSString *emailBody = [NSString stringWithFormat:@"<font color='red'>%@\ncrashTime：%@</font>", crashInfo[@"crashString"],crashInfo[@"timeString"]];
    
    [mailPicker setMessageBody:emailBody isHTML:YES];
    [self presentViewController:mailPicker animated:YES completion:nil];
}

#pragma mark - 实现 MFMailComposeViewControllerDelegate

- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error {
    
    //关闭邮件发送窗口
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSString *msg;
    
    switch (result) {
        case MFMailComposeResultCancelled:
            msg = @"用户取消编辑邮件";
            break;
        case MFMailComposeResultSaved:
            msg = @"用户成功保存邮件";
            break;
        case MFMailComposeResultSent:
            msg = @"用户点击发送，将邮件放到队列中，还没发送";
            break;
        case MFMailComposeResultFailed:
            msg = @"用户试图保存或者发送邮件失败";
            break;
        default:
            msg = @"";
            break;
    }
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:msg message:nil delegate:nil cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
    [alertView show];
}

-(HDEETableCellModel *) cellInfo
{
    HDEETableCellModel *model = [HDEETableCellModel model];
    model.cellTitle = @"跳转至崩溃列表";
    model.type = kHDEasterEggsCellTypeForJumpToVC;
    model.identifier = NSStringFromClass([self class]);
    return model;
}

@end
